package com.yy.myp.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.room.Room;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.baidu.mapapi.search.sug.SuggestionSearch;
import com.baidu.mapapi.search.sug.SuggestionSearchOption;
import com.yy.myp.R;
import com.yy.myp.adapter.MapSearchItemAdapter;
import com.yy.myp.common.CommonConstant;
import com.yy.myp.database.AppDatabase;
import com.yy.myp.dto.LocalPositionDto;
import com.yy.myp.entity.MapSearchItem;
import com.yy.myp.utils.GPSUtil;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

public class MapActivity extends AppCompatActivity {

    private MapView mMapView = null;

    private MapSearchItem mapSearchItem = null;

    private AppCompatButton btnAddPosition;

    private AppDatabase db;

    private SuggestionSearch mSuggestionSearch;

    private RecyclerView mMapSearchList;

    private MapSearchItemAdapter mapSearchItemAdapter;

    private EditText etMapSearch;

    private TextView tvAddress;

    private TextView tvDetail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);

        initBaiduMap();

        btnAddPosition = findViewById(R.id.btn_add_position);
        tvAddress = findViewById(R.id.at_map_tv_address);
        tvDetail = findViewById(R.id.at_map_tv_detail);

        btnAddPosition.setOnClickListener( v -> {
            if (null == mapSearchItem) {
                Toast.makeText(this, "请在地图种选择添加的地点", Toast.LENGTH_SHORT).show();
                return;
            }
            Intent intent = getIntent();
            mMapView.getMap().snapshot( bitmap -> {
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);

                LocalPositionDto positionDto = new LocalPositionDto();
                int uid = (int) System.currentTimeMillis();
                positionDto.setUid(uid);
                positionDto.setLatitude(mapSearchItem.getPt().latitude);
                positionDto.setLongitude(mapSearchItem.getPt().longitude);
                positionDto.setPosName(mapSearchItem.getKey());
                positionDto.setBitmap(os.toByteArray());

                db.positionDao().insertAll(positionDto);

                Bundle bundle = new Bundle();
                bundle.putInt("localPosId", uid);
                intent.putExtras(bundle);
                setResult(RESULT_OK, intent);
                finish();
            });
        });

        mMapSearchList = findViewById(R.id.at_map_list);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mMapSearchList.setLayoutManager(linearLayoutManager);
        mapSearchItemAdapter = new MapSearchItemAdapter(this);
        mMapSearchList.setAdapter(mapSearchItemAdapter);
        mapSearchItemAdapter.setOnClickListener( v -> {
            mapSearchItemAdapter.setAddressList(new ArrayList<>());
            if (null == v) {
                return;
            }
            MapStatus mMapStatus = new MapStatus.Builder()
                    .target(v.getPt())
                    .zoom(18)
                    .build();
            MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
            //改变地图状态
            mMapView.getMap().setMapStatus(mMapStatusUpdate);
            drawMarker(v.getPt());
            mapSearchItem = v;

            etMapSearch.clearFocus();
            tvAddress.setText(v.getKey());
            tvAddress.setVisibility(View.VISIBLE);
            tvDetail.setText(v.getAddress());
            tvDetail.setVisibility(View.VISIBLE);
        });

        etMapSearch = findViewById(R.id.at_et_map_search);
        etMapSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                Log.v("TAG", "用户输入了: " + s.toString());
                String input = s.toString().trim();
                if (null == input || "".equals(input)) {
                    mapSearchItemAdapter.setAddressList(new ArrayList<>());
                    return;
                }
                mSuggestionSearch.requestSuggestion(new SuggestionSearchOption()
                        .city("重庆")
                        .keyword(input));
            }
        });

        db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, CommonConstant.DB_NAME).allowMainThreadQueries().build();

    }

    private void initBaiduMap() {
        mMapView = findViewById(R.id.bmapView);

        mMapView.getMap().setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                Log.v("TAG", "地图点击了 " + latLng.latitude);
                mapSearchItem = new MapSearchItem();
                mapSearchItem.setPt(latLng);
                mapSearchItem.setKey("手动选择!");

                drawMarker(latLng);
            }

            @Override
            public void onMapPoiClick(MapPoi mapPoi) {
                Log.v("TAG", "地图点击了 " + mapPoi.getName());
            }
        });

        double[] bPoint = GPSUtil.gps84_To_bd09(29.536596, 106.507997);
        LatLng cenpt = new LatLng(bPoint[0], bPoint[1]);
        MapStatus mMapStatus = new MapStatus.Builder()
                .target(cenpt)
                .zoom(18)
                .build();
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
        //改变地图状态
        mMapView.getMap().setMapStatus(mMapStatusUpdate);

        mSuggestionSearch = SuggestionSearch.newInstance();
        mSuggestionSearch.setOnGetSuggestionResultListener(v -> {
            Log.v("TAG", "检索地点");
            List<SuggestionResult.SuggestionInfo> allSuggestions = v.getAllSuggestions();
            List<MapSearchItem> address = new ArrayList<>();
            for (SuggestionResult.SuggestionInfo suggestionInfo : allSuggestions) {
                MapSearchItem searchItem = new MapSearchItem();
                searchItem.setKey(suggestionInfo.key);
                searchItem.setAddress(suggestionInfo.address);
                searchItem.setPt(suggestionInfo.pt);
                searchItem.setTag(suggestionInfo.getTag());
                searchItem.setUid(suggestionInfo.getUid());

                address.add(searchItem);
            }
            mapSearchItemAdapter.setAddressList(address);
        });
    }


    private void drawMarker (LatLng pLatLng) {
        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromBitmap(getBitmap(getApplicationContext(), R.drawable.position));
        //构建MarkerOption，用于在地图上添加Marker
        MarkerOptions posOverlay = new MarkerOptions()
                .position(pLatLng)
                .icon(bitmap);

        //在地图上添加Marker，并显示
//                mMapView.getMap().removeOverLays(Arrays.asList(posOverlay));
        mMapView.getMap().clear();
        mMapView.getMap().addOverlay(posOverlay);
    }


    private static Bitmap getBitmap(Context context, int vectorDrawableId) {
        Bitmap bitmap=null;
        if (Build.VERSION.SDK_INT>Build.VERSION_CODES.LOLLIPOP){
            Drawable vectorDrawable = context.getDrawable(vectorDrawableId);
            bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(),
                    vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
            vectorDrawable.draw(canvas);
        }else {
            bitmap = BitmapFactory.decodeResource(context.getResources(), vectorDrawableId);
        }
        return bitmap;
    }


    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
        mSuggestionSearch.destroy();
    }

}